<?php
declare(strict_types = 1);

namespace app\common\controller\admin;

use app\common\controller\AdminBase;
use app\common\model\UserGroup;
use app\common\wormview\AddEditList;
use app\facade\hook\Common;
use think\exception\ValidateException;
use worm\NodeFormat;

abstract class Part extends AdminBase {
    use AddEditList;
    protected $basename;
    protected $ArtMdodelBase;
    protected $ArtMdodelList;
    protected $list_temp = null;
    protected $list_page = false;
    protected function initialize(){
        parent::initialize();
        //  定义模型
        preg_match_all('/([_a-z]+)/',toUnderScore(get_called_class()),$array);
        $this->basename = $array['0']['3'];
        $mdodel = "app\\common\\model\\".$this->basename."\\".ucfirst($array['0']['4']);
        $ArtMdodelBase = "app\\common\\model\\".$this->basename."\\Artmodel";
        $this->validate = "app\\common\\validate\\ArtPart";
        $this->model = new $mdodel;
        $this->ArtMdodelBase = new $ArtMdodelBase;
        $this->contauth = $this->CheckAuth('create,edit,del');
        $this->list_base['page'] = '1';
        $this->list_base['open'] = 'false';
        $this->getConf();
    }
    protected function getMap(){
        $mid = empty($this->getdata['mid']) ? array_column($this->ArtMdodelList,'id') : $this->getdata['mid'];
        $map = [
            'mid' => empty($mid) ? 'no' : $mid,
            'del_time' => empty($this->getdata['del_time']) ? '' : $this->getdata['del_time'],
            'status' => empty($this->getdata['status']) ? 'a' : $this->getdata['status'],
        ];
        return array_merge(parent::getMap(),$map); // TODO: Change the autogenerated stub
    }

    protected function getConf(){
        if($this->contauth['create']) {
            $this->list_base['add'] = ['title' => '添加栏目', 'class' => 'cx-button-s cx-bg-green'];
        }
         //  获取模型
        $this->ArtMdodelList = $this->ArtMdodelBase->getList(['status' => '1']);
        if(empty($this->ArtMdodelList)){
            $this->error("请先创建模型", url("{$this->basename}.artmodel/index")->build());
        }
        $getfu = [];
        if(!empty($this->getdata['mid'])){
            $getfu['mid'] = $this->getdata['mid'];
            $_model = Common::del_file($this->ArtMdodelList,'id',$this->getdata['mid']);
            if(empty($_model)){
                $this->ArtMdodelList = $this->ArtMdodelBase->getList(['id' => $this->getdata['mid'],'getdeltime' => '1001','status' => 'a']);
            }
        }
        $_modellist = [];
        $_field = [['title' => '全部','value'=>'']];
        if(!empty($this->ArtMdodelList)){
            foreach ($this->ArtMdodelList as $k => $v){
                $_modellist[$v['id']] = empty($v['futitle']) ? $v['title'] : $v['futitle'];
                $_field[] = ['title' => empty($v['futitle']) ? $v['title'] : $v['futitle'],'value' => $v['id']];
            }
        }
        $this->list_file = [['file' => 'id','title' => 'ID','type' => 'text','textalign' => 'center','width' => '80'],
            ['file' => 'title','title' => '栏目名称','type' => 'text','width' => '20%'],
            ['file' => 'article_num','title' => '内容数量','width' => '120','textalign' => 'center','type' => 'link','uri' => url($this->basename.'.article/index',['fid'=>'__id__'])->build(),],
            ['file' => 'mid','title' => '所属模型','width' => '120','textalign' => 'center','type' => 'radio','data' => $_modellist],
            ['file' => 'class','title' => '类型','width' => '80','textalign' => 'center','type' => 'radio','data' => ['0' => '栏目','1' => '单篇']],
            ['file' => 'sort','title' => '排序','type' => 'edit','textalign' => 'center','width' => '80',],
            ['file' => 'status','title' => '状态','type' => 'switch','text' => '启用|禁用','textalign' => 'center','width' => '100','default' => '1']];
        if($this->request->action() == 'index'){
            $this->list_base['uri'] = url('getlist',empty($this->getdata['mid']) ? [] : ['mid' => $this->getdata['mid']])->build();
            $this->list_file[] = ['file' => 'class','file_edit' => 'article','title' => '发表内容','type' => 'radio','type_edit' => 'link','text' => true,'open' => true,'opentitle' => "发表内容",'data' => ['0' => ['uri' => url($this->basename.'.article/create',['fid' => '__id__'])->build(),'icon' => 'cx-iconedit cx-text-f16','class' => 'cx-text-black']],'textalign' => 'center','width' => '100','full' => 'y'];
            if($this->contauth['create']) {
                $this->list_file[] = ['file' => 'class','title' => '子栏目','type' => 'radio','type_edit' => 'link','text' => true,'open' => true,'opentitle' => "添加子栏目",'data' => ['0' => ['uri' => url('create',['pid' => '__id__'])->build(),'icon' => 'cx-iconadd cx-text-f16','class' => 'cx-text-black']],'textalign' => 'center','width' => '80'];
            }
            if($this->contauth['edit']){
                $this->list_file[] = ['filed' => 'edit','title' => '编辑','type' => 'btn','text' => true,'open' => true,'opentitle' => "编辑栏目",'uri' => url('edit',['id' => '__id__'])->build(),'icon' => 'cx-iconbianji3 cx-text-f16','class' => 'cx-text-green','textalign' => 'center','width' => '80'];
            }
            if($this->contauth['del']){
                $this->list_file[] = ['filed' => 'del','title' => '删除','type' => 'btn','event' => 'del','text' => true,'icon' => 'cx-iconlajixiang cx-text-f16','class' => 'cx-text-red','textalign' => 'center','width' => '80'];
                $this->list_top = [
                    ['title' => '回收站', 'class' => 'cx-button-s cx-bg-yellow cx-mag-r10','uri' => url('trash')->build()],
                ];
            }
            $this->list_search = [
                'fieldname' => 'mid',
                'field' => $_field,
                'uri' => url('getlist')->build(),
            ];

        }else if(in_array($this->request->action(),['edit','create'])){
             $_fid = empty($this->getdata['fid']) ? '0' : $this->getdata['fid'];
            $this->list_base['uri'] = url('save',$this->request->action() == 'create' ? ['fid' => $_fid] : ['fid' => $_fid,'id' => $this->getdata['id']]);
            $usermodel = new UserGroup();
            $group_list = $usermodel->getList([]);
            $new_group_list = $get_group_list = [];
            if(!empty($group_list)){
                foreach ($group_list as $k => $v){
                    $new_group_list[$v['id']] = $v['title'];
                }
                $get_group_list = Common::del_file($group_list,'group_admin','1');
                $get_group_list = array_column($get_group_list,'id');
            }
            $get_group_list = empty($get_group_list) ? 'a' : implode('|',$get_group_list);
            //  获取所有上级栏目
            $listdb = $this->model->getList();
            if(!empty($this->getdata['pid'])){
                $ids = NodeFormat::getChildsId($listdb,$this->getdata['pid']);
                foreach ($listdb as $k => $v){
                    if(in_array($v['id'],$ids) || $v['class'] == '1'){
                        unset($listdb[$k]);
                    }
                    continue;
                }
            }
            $_ids = [];
            if(!empty($this->getdata['id'])){
                $_ids = Common::del_file($listdb,'id',$this->getdata['id']);
                if(!empty($_ids['0'])){
                    $_ids = $_ids['0'];
                    $ids = NodeFormat::getChildsId($listdb,$this->getdata['id']);
                    array_push($ids,$this->getdata['id']);
                    foreach ($listdb as $k => $v){
                        if(in_array($v['id'],$ids)){
                            unset($listdb[$k]);
                        }
                        continue;
                    }
                }
            }
            $listdb = NodeFormat::toList($listdb);
            $_listdb =[];
            if(!empty($listdb)){
                foreach ($listdb as $k => $v){
                    if($v['class'] == '1'){
                        continue;
                    }
                    if(!empty($this->getdata['id']) && $v['id'] == $this->getdata['id']){
                        continue;
                    }
                    $_listdb[$v['id']] = $v['title_display'];
                }
                $listdb = $_listdb;
                unset($_listdb);
            }
            $_temp = getDirlist(root_path('view/home'));
            $_list = [];
            foreach ($_temp as $k => $v){
                $_v = root_path("view/home/{$v}")."{$v}.php";
                if(!is_file($_v)){
                    continue;
                }
                $_v = require $_v;
                $_list[$v] = $_v['name'];
            }
            $this->form_list = !empty($_ids) && $_ids['class'] == '1' ? [
                ['file' => 'pid','title' => '上级栏目','text_edit' => '顶级栏目','type' => 'select','data' => ['list' => $listdb,'default' => empty($this->getdata['pid']) ? '0' : (int) $this->getdata['pid']],'tip' => "如不选择则为顶级栏目"],
                ['file' => 'title','title' => '栏目名称','type' => 'text','required' => true],
                ['file' => 'mid','title' => '选择模型','type' => 'select','data' => ['list' => $_modellist,'default' => '','default_edit' => '1'],'required' => true,'required_list' => 'number'],
                ['file' => 'class','title' => '栏目类型','type' => 'radio','data' =>['list' => ['0' => '栏目','1' => '单篇文章',],'default' => '0']],
                ['file' => 'description','title' => '内容','type' => 'editor'],
                ['file' => 'status','title' => '是否启用','type' => 'radio','data' =>['list' => ['0' => '关闭栏目','1' => '启用栏目',],'default' => '1']],
                ['file' => 'jumpurl','title' => '跳转地址','type_group' => 'SEO及风格','type' => 'text','tip' => '要加http://或https://,如：http://www.cxbs.net'],
                ['file' => 'keywords','title' => 'SEO关键词','type_group' => 'SEO及风格','type' => 'text','tip' => '多个关键词请用英文’,‘进行分割，推荐80字以内',],
                ['file' => 'banber','title' => 'BANBER','type_group' => 'SEO及风格','type' => 'upload','upload_filenum' => '1','upload_autoup' => '1'],
                ['file' => 'logo','title' => 'LOGO','type_group' => 'SEO及风格','type' => 'upload','upload_filenum' => '1','upload_autoup' => '1'],
                ['file' => 'password','title' => '栏目密码','type_group' => 'SEO及风格','type' => 'text','tip' => '设置密码后，本栏目所有内容均会加密'],
                ['file' => 'temp_late','title' => '自订义风格','type_group' => 'SEO及风格','type' => 'select','data' => ['list' => $_list,'default' => '']],
                ['file' => 'temp_head','title' => '自订义头部','type_group' => 'SEO及风格','type' => 'text','tip' => '独立头部风格，如：default/new_head.htm'],
                ['file' => 'temp_list','title' => '自订义列表','type_group' => 'SEO及风格','type' => 'text','tip' => '独立列表页风格，如：default/new_list.htm'],
                ['file' => 'temp_cont','title' => '自订义内容页','type_group' => 'SEO及风格','type' => 'text','tip' => '独立内容页风格，如：default/new_article.htm'],
                ['file' => 'temp_foot','title' => '自订义底部','type_group' => 'SEO及风格','type' => 'text','tip' => '独立底部风格，如：default/new_foot.htm'],
                ['file' => 'limit','title' => '列表显示','type' => 'text','type_edit' => 'hidden','type_unit' => '条','default' => '0'],
                ['file' => 'title_num','title' => '内容标题显示','type' => 'text','type_edit' => 'hidden','type_unit' => '字','default' => '0'],
                ['file' => 'cont_num','title' => '内容简介显示','type' => 'text','type_edit' => 'hidden','type_unit' => '字','default' => '0'],
                ['file' => 'pid_see','title' => '上级栏目显示','type' => 'text','type_edit' => 'hidden','type_unit' => '字','default' => '0'],
                ['file' => 'comment_see','title' => '评论','type' => 'text','type_edit' => 'hidden','type_unit' => '字','default' => '0'],
                ['file' => 'order','title' => '排序','type' => 'text','type_edit' => 'hidden','default' => 'top desc,jian desc,addtime desc'],
                ['file' => 'sort','title' => '排序值','type' => 'text','required' => true,'default' => '0'],
            ] : [
                ['file' => 'title','title' => '栏目名称','type' => 'text','required' => true],
                ['file' => 'class','title' => '栏目类型','type' => 'radio','data' =>['list' => ['0' => '栏目','1' => '单篇文章',],'default' => '0']],
                ['file' => 'pid','title' => '上级栏目','text_edit' => '顶级栏目','type' => 'select','data' => ['list' => $listdb,'default' => empty($this->getdata['pid']) ? '0' : (int) $this->getdata['pid']],'tip' => "如不选择则为顶级栏目"],
                ['file' => 'mid','title' => '选择模型','type' => 'select','data' => ['list' => $_modellist,'default' => '','default_edit' => '1'],'required' => true,'required_list' => 'number'],
                ['file' => 'order','title' => '排序','type' => 'select','data' => ['list' => ['top desc,jian desc,addtime desc' => '默认排序','sort desc' => '排序值降序','sort asc' => '排序值升序','id desc' => '发表时间降序','id asc' => '发表时间升序','hist desc' => '点击量降序','hist asc' => '点击量升序',],'default' => '','default_edit' => '1'],'required' => true],
                ['file' => 'limit','title' => '列表显示','type' => 'text','type_edit' => 'number','type_unit' => '条','default' => '0','required' => true,'required_list' => 'number'],
                ['file' => 'title_num','title' => '内容标题显示','type' => 'text','type_edit' => 'number','type_unit' => '字','default' => '0','required' => true,'required_list' => 'number'],
                ['file' => 'cont_num','title' => '内容简介显示','type' => 'text','type_edit' => 'number','type_unit' => '字','default' => '0','required' => true,'required_list' => 'number'],
                ['file' => 'pid_see','title' => '上级栏目显示','type' => 'radio','data' =>['list' => ['0' => '隐藏','1' => '显示',],'default' => '1']],
                ['file' => 'comment_see','title' => '评论','type' => 'radio','data' =>['list' => ['0' => '关闭评论','1' => '开启评论',],'default' => '1']],
                ['file' => 'group_uid','title' => '管理员','type' => 'callcont','form_geturi' => "api/user/userlist?u_groupid={$get_group_list}",'form_geturitype' => '1','form_js' => 'title=u_uname,value=uid','tip' => '不选则所有管理员有权限',],
                ['file' => 'group_see','title' => '允许查看','type' => 'checkbox','data' =>['list' => $new_group_list,'default' => '']],
                ['file' => 'group_edit','title' => '允许编辑','type' => 'checkbox','data' =>['list' => $new_group_list,'default' => '']],
                ['file' => 'status','title' => '是否启用','type' => 'radio','data' =>['list' => ['0' => '关闭栏目','1' => '启用栏目',],'default' => '1']],
                ['file' => 'sort','title' => '排序值','type' => 'text','required' => true,'default' => '0'],
                ['file' => 'jumpurl','title' => '跳转地址','type_group' => 'SEO及风格','type' => 'text','tip' => '要加http://或https://,如：http://www.cxbs.net'],
                ['file' => 'keywords','title' => 'SEO关键词','type_group' => 'SEO及风格','type' => 'text','tip' => '多个关键词请用英文’,‘进行分割，推荐80字以内',],
                ['file' => 'description','title' => 'SEO描述','type_group' => 'SEO及风格','type' => 'textarea','tip' => '推荐200字以内',],
                ['file' => 'banber','title' => 'BANBER','type_group' => 'SEO及风格','type' => 'upload','upload_filenum' => '1','upload_autoup' => '1'],
                ['file' => 'logo','title' => 'LOGO','type_group' => 'SEO及风格','type' => 'upload','upload_filenum' => '1','upload_autoup' => '1'],
                ['file' => 'password','title' => '栏目密码','type_group' => 'SEO及风格','type' => 'text','tip' => '设置密码后，本栏目所有内容均会加密'],
                ['file' => 'temp_late','title' => '自订义风格','type_group' => 'SEO及风格','type' => 'select','data' => ['list' => $_list,'default' => '']],
                ['file' => 'temp_head','title' => '自订义头部','type_group' => 'SEO及风格','type' => 'text','tip' => '独立头部风格，如：default/new_head.htm'],
                ['file' => 'temp_list','title' => '自订义列表','type_group' => 'SEO及风格','type' => 'text','tip' => '独立列表页风格，如：default/new_list.htm'],
                ['file' => 'temp_cont','title' => '自订义内容页','type_group' => 'SEO及风格','type' => 'text','tip' => '独立内容页风格，如：default/new_article.htm'],
                ['file' => 'temp_foot','title' => '自订义底部','type_group' => 'SEO及风格','type' => 'text','tip' => '独立底部风格，如：default/new_foot.htm'],
            ];
            if($this->request->action() == 'edit'){
                $phsh = [
                    ['file' => 'id','title' => 'ID','type' => 'text','type_edit' => 'hidden','required' => true,'required_list' => 'number',],
                    ['file' => '_method','title' => 'ID','type' => 'text','type_edit' => 'hidden','required' => true,'default' => 'PUT',]
                ];
               $this->form_list = array_merge($this->form_list,$phsh);
            }
         }else if($this->request->action() == 'trash'){
            $this->list_base['uri'] = url('getlist',['del_time' => '1001','status' => 'a'])->build();
            if ($this->contauth['edit']) {
                $this->list_file[] = ['filed' => 'trash', 'title' => '还原', 'type' => 'btn', 'text' => true, 'event' => 'trash', 'opentitle' => "编辑栏目", 'uri' => url('trashone', ['id' => '__id__'])->build(), 'icon' => 'cx-iconhuanyuan1 cx-text-f16', 'class' => 'cx-text-green', 'textalign' => 'center', 'width' => '80', 'fixed' => 'right','full' => 'y'];
            }
            if($this->contauth['del']){
                $this->list_file[] = ['filed' => 'del','title' => '删除','type' => 'btn','event' => 'del','text' => true,'icon' => 'cx-iconlajixiang cx-text-f16','class' => 'cx-text-red','textalign' => 'center','width' => '80'];
            }
            $this->list_base['page'] = '2';
             $this->list_base['add'] = false;
             $this->list_top = [
                 ['title' => '栏目列表', 'class' => 'cx-button-s cx-bg-blue cx-mag-r10','uri' => url('index')->build()],
             ];
         }
    }
    public function getlist()
    {
        $map = $this->getMap();
        if($this->wormuser['u_groupid'] != '1'){
            $map['group_see'] = $this->wormuser['u_groupid'];
        }
        $getlist = $this->model->getList($map);
        if(empty($this->getdata['del_time'])){
            $getlist = NodeFormat::toList($getlist);
        }
        return $this->viewAdminList($getlist);
    }
    public function edit($id)
    {
        $getlist = $this->model->getOne($this->getdata['id']);
        if(empty($getlist)){
            $this->error("栏目不存在");
        }
        if($this->wormuser['u_groupid'] != '1' && !empty($getlist['group_edit']) && !in_array($this->wormuser['u_groupid'],explode(',',$getlist['group_edit']))){
            $this->error("没有此权限");
        }
        return $this->viewAdminAdd($getlist);
    }
    //  保存数据
    public function save(){
        if(!$this->request->isPost() && !$this->request->isPut()){
            $this->error("非法访问");
        }
        $data = Common::data_trim(input('post.'));
        if($this->request->isPut() && empty($data['id'])){
            $this->error("非法访问");
        }
        try {
            validate($this->validate)->scene($this->request->isPut() ? "edit" : "add")->check($data);
        }catch (ValidateException $e){
             $this->error($e->getError());
        }
        $data = Common::data_trim(input('post.'));
        $data = $this->model->EditAdd($data);
        if($this->request->isPut() && $data['class'] == '1'){
            $res = $this->model->getList();
            if(!empty(NodeFormat::getChildsId($res,$data['id']))){
                $this->error("存在下级栏目，不可修改栏目类型");
            }
            $res = Common::del_file($res,'id',$data['id']);
            if($res['0']['article_num'] > '0'){
                $this->error('栏目存在内容，不可修改栏目类型');
            }
        }
        $res_title = $this->request->isPut() ? "编辑" : "添加";
        if($add = $this->model->setOne($data)){
            $_fid = !empty($this->getdata['fid']) ? $this->getdata['fid'] : '0';
            $this->success("{$res_title}成功",url('index',['fid' => $_fid])->build(),$add);
        }
        $this->error("{$res_title}失败");
    }
    public function pdel(){
        $data = Common::data_trim(input('post.'));
        if(empty($data['ids'])){
            $this->error("非法访问");
        }
        $res = $this->model->DeleteOne($data['ids']);
        if($res === true || !empty($res['code'])){
            $this->success("删除成功");
        }
        $this->error(empty($res['msg']) ? '删除失败' : $res['msg']);
    }
}